<?php

use think\Cache;
use think\Db;

// 异常错误报错级别,
error_reporting(E_ERROR | E_PARSE);

function C($name)
{
	$config = cache('systemConfig');
	if ($config) {
		$value = '';
		foreach ($config as &$v) {
			if ($v['name'] == $name) {
				$value = $v['output_value'];
				break;
			}
		}

		return $value;
	} else {
		$config = Db::name('config')->where(['name' => $name])->order('sort asc')->value('value');

		return $config;
	}
}

/**
 * 系统加密方法
 * @param        string        $data          要加密的字符串
 * @param        int           $expire        过期时间 (单位:秒)
 * @return string
 */
function thinkEncrypt($data, $expire = 0)
{
	$key = md5('083d9a270e6e16b2fbb08d35067aae5f');
	$data = base64_encode($data);
	$x = 0;
	$len = strlen($data);
	$l = strlen($key);
	$char = '';
	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}
	$str = sprintf('%010d', $expire ? $expire + time() : 0);
	for ($i = 0; $i < $len; $i++) {
		$str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
	}

	return str_replace('=', '', base64_encode($str));
}

/**
 * 系统解密方法
 * @param        string        $data        要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @return string
 */
function thinkDecrypt($data)
{
	$key = md5('083d9a270e6e16b2fbb08d35067aae5f');
	$x = 0;
	$data = base64_decode($data);
	$expire = substr($data, 0, 10);
	$data = substr($data, 10);
	if ($expire > 0 && $expire < time()) {
		return '';
	}
	$len = strlen($data);
	$l = strlen($key);
	$char = $str = '';
	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}
	for ($i = 0; $i < $len; $i++) {
		if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
			$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
		} else {
			$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
		}
	}

	return base64_decode($str);
}

/**
 * 检查验证码
 * */
function checkVerify($code)
{
	$verify = new \think\captcha\Captcha();

	return $verify->check($code);
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl()
{
	if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
		return true;
	} else if (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
		return true;
	}

	return false;
}

/**
 * 获取域名前缀
 * */
function getHost()
{
	$res = is_ssl();
	if ($res) {
		return 'https://' . $_SERVER['HTTP_HOST'];
	} else {
		return 'http://' . $_SERVER['HTTP_HOST'];
	}
}

/**
 * 按综合方式输出通信数据
 * @param        integer        $result        状态码
 * @param        string         $msg           提示信息
 * @param        array          $data          数据
 * @return string
 */
function apiReturn($result, $msg = '', $data = false)
{
	if (!is_numeric($result)) {
		return '';
	}

	return apiJson($result, $msg, $data);
}

/**
 * 按json方式输出通信数据
 * @param        integer        $result        状态码
 * @param        string         $msg           提示信息
 * @param        array          $data          数据
 * @return string
 */
function apiJson($result, $msg = '', $data = false)
{

	if (!is_numeric($result)) {
		return '';
	}

	if ($data > 0 || $data === []) {
		$message = array(
			'result' => $result,
			'msg' => $msg,
			'data' => $data ? $data : []
		);
	} else {
		$message = array(
			'result' => $result,
			'msg' => $msg,
			'data' => $data ? $data : ''
		);
	}

	echo json_encode($message, JSON_UNESCAPED_UNICODE);
	exit;
}

/**
 * 根据图片id获取图片路径
 * */
function getPicture($id)
{
	if (preg_replace('/\D/s', '', $str) == $str) {
		//ID
		$info = Db::name('picture')->field('path')->where(['id' => $id])->find();
		if ($info) {
			return getHost() . $info['path'];
		} else {
			return '';
		}
	} else {
		//路径
		return $id;
	}
}

/**
 * 用户头像处理
 * @param        int        $avatar_id        用户头像ID 或 用户头像路径
 * @return string
 * */
function doAvatar($avatar_id)
{
	if (strlen($avatar_id) < 10) {
		//此时用户头像为修改之后的头像
		$avatar = getPicture($avatar_id);
	} else {
		$avatar = $avatar_id;
	}

	return $avatar ? $avatar : '';
}

/**
 * 多图处理
 * @param        string        $imgs           图片id集合
 * @param        string        $img_key        自定义图片路径下标
 * @return array
 * */
function doImgs($imgs, $img_key = 'path')
{
	$new_img_arr = [];
	if ($imgs) {
		$img_arr = explode(',', $imgs);

		if ($img_arr) {
			foreach ($img_arr as $k => &$v) {
				$new_img_arr[$k]['id'] = $v;
				$new_img_arr[$k][$img_key] = getPicture($v);
			}
		}
	}

	return $new_img_arr;
}

/**
 * 获取[规格-属性]数据
 * @param        int        $goods_id        商品id
 * @return array
 * */
function getSku($goods_id)
{
	if (!cache('sku_' . $goods_id)) {
		$sku_value_list = Db::name('sku_value')->where(['goods_id' => $goods_id])->select();

		//$skus_id_arr：所有属性的id集合
		$skus_id_arr = [];
		if ($sku_value_list) {
			foreach ($sku_value_list as &$val) {
				$val['img'] = getPicture($val['img']);

				$sku_id = explode('-', $val['sku_id']);
				if ($sku_id) {
					foreach ($sku_id as &$value) {
						if (!in_array($value, $skus_id_arr)) {
							$skus_id_arr[] = $value;
						}
					}
				}
			}

			$parent_list = Db::name('sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr]])->select();
			$parent_ids = array_column($parent_list, 'pid');
			if ($parent_ids) {
				$sku_list = Db::name('sku')->field('id,name title')->where(['id' => ['IN', $parent_ids]])->select();
				if ($sku_list) {
					foreach ($sku_list as &$v) {
						$child_list = Db::name('sku')->field('id,name title')->where(['pid' => $v['id']])->select();
						if ($child_list) {
							foreach ($child_list as &$val) {
								$val['class'] = '';
								$val['status'] = false;
								foreach ($sku_value_list as &$value) {
									if (in_array($val['id'], explode('-', $value['sku_id'])) && $value['status']) {
										$val['status'] = true;
										break;
									}
								}
							}
						} else {
							$child_list = [];
						}
						$v['child'] = $child_list;
					}
				} else {
					$sku_list = [];
				}
			}
		} else {
			$sku_value_list = [];
		}

		$data = [
			'sku_list' => $sku_list,
			'sku_value_list' => $sku_value_list
		];
		cache('sku_' . $goods_id, $data);
	} else {
		$data = cache('sku_' . $goods_id);
	}

	return $data;
}

/**
 * 微信违规文字检测
 * */
function checkContent($content)
{
	if ($access_token = accessToken()) {
		$checkUrl = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $access_token;
		$arr = [
			'content' => $content
		];

		$result = httpRequest($checkUrl, $arr, 'json');
		$result = json_decode($result, true);

		if ($result['errcode'] != 0) apiReturn(2, '检测到文字含违规内容，请重新编辑');
	} else {
		apiReturn(2, 'access_token获取失败');
	}
}

function accessToken()
{
	$appid = C('XCX_APPID');
	$secret = C('XCX_SECRET');
	$tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
	$tokenArr = file_get_contents($tokenUrl);
	$tokenArr = json_decode($tokenArr, true);

	return $tokenArr['access_token'];
}

function httpRequest($url, $data, $type)
{
	if ($type == 'json') {
		$headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
		$data = json_encode($data, JSON_UNESCAPED_UNICODE);
	} else {
		$headers = [];
	}
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	if (!empty($data)) {
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	$output = curl_exec($curl);
	curl_close($curl);

	return $output;
}

/**
 * 一维数组去重
 * */
function a_array_unique($array)
{
	$out = array();
	foreach ($array as $key => $value) {
		if (!in_array($value, $out)) {
			$out[$key] = $value;
		}
	}

	return $out;
}

/**
 * 处理富文本信息
 * @param        string        $content        富文本内容
 * @return  string
 * */
function doEditorContent($content)
{
	return $content ? str_replace('<img src="', ' < img style = "width: 100%; height: auto" src = "' . getHost(), $content) : '';
}

/**
 * 格式化时间
 * @param        int         $time        时间戳
 * @param        date        $date        时间格式
 * */
function timeFormat($time, $date = 'Y-m-d H:i:s')
{
	if ($time) {
		return date($date, $time);
	} else {
		return '';
	}
}

/**
 * @param        array        $sku_id        属性id集合
 * @return string
 * */
function getSkuName($sku_id)
{
	if ($sku_id) {
		$in_sku = implode(',', $sku_id);
		$order = ' field (id, ' . $in_sku . ' ) ';
		$sql = 'SELECT `name` FROM `tp_sku` WHERE `id` IN(' . $in_sku . ') ORDER BY ' . $order;
		$sku_list = Db::query($sql);

		return $sku_list;
	} else {
		return '';
	}
}

/**
 * 获取省id
 * @param        string        $province_name        省名称
 * @return int
 * */
function getProvinceId($province_name)
{
	$province_id = Db::name('province')->where(['name' => $province_name])->value('province_id');

	return $province_id;
}

/**
 * 获取省名称
 * @param        int        $province_id        省id
 * @return string
 * */
function getProvinceName($province_id)
{
	$name = Db::name('province')->where(array('province_id' => $province_id))->value('name');

	return $name ? $name : '';
}

/**
 * 获取市id
 * @param        string        $province_name        省名称
 * @param        string        $city_name            市名称
 * @return int
 * */
function getCityId($province_name, $city_name)
{
	$province_id = getProvinceId($province_name);

	$city_name = str_replace(array('市', '省'), '', $city_name);
	$city_id = Db::name('city')->where(array('province_id' => $province_id, 'name' => array('like', $city_name . '%')))->value('city_id');

	return $city_id;
}

/**
 * 获取市名称
 * @param        int        $city_id        市id
 * @return string
 * */
function getCityName($city_id)
{
	$name = Db::name('city')->where(array('city_id' => $city_id))->value('name');

	return $name ? $name : '';
}

/**
 * 获取区id
 * @param        string        $province_name        省名称
 * @param        string        $city_name            市名称
 * @param        string        $area_name            市名称
 * @return int
 * */
function getAreaId($province_name, $city_name, $area_name)
{
	$city_id = getCityId($province_name, $city_name);

	$area_name = str_replace(array('市', '区', '县'), '', $area_name);
	$area_id = Db::name('area')->where(array('city_id' => $city_id, 'name' => array('like', $area_name . '%')))->value('area_id');

	return $area_id;
}

/**
 * 获取区名称
 * @param        int        $area_id        区id
 * @return string
 * */
function getAreaName($area_id)
{
	$name = Db::name('area')->where(array('area_id' => $area_id))->value('name');

	return $name ? $name : '';
}

function httpsRequest($url, $data = null)
{
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	if (!empty($data)) {
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($curl);
	curl_close($curl);

	return $output;
}

/**
 * 获取access_token
 * @param        string        $token_file_name        token存储文件名
 * @param        int           $type                   1:公众号token，2：小程序token
 * @return string
 *  */
function get_access_token($token_file_name = 'access_token.json', $type = 1, &$count = 0)
{
	if ($type == 1) {
		$config = [
			'appid' => C('GZH_APPID'),
			'secret' => C('GZH_SECRET'),
		];
	} else {
		$config = [
			'appid' => C('XCX_APPID'),
			'secret' => C('XCX_SECRET'),
		];
	}

	// access_token 应该全局存储与更新，以下代码以写入到文件中做示例
	$data = json_decode(get_php_file($token_file_name));
	if ($data->expires_time < time()) {
		// 如果是企业号用以下URL获取access_token
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $config['appid'] . "&secret=" . $config['secret'];
		$access_token_json = httpsRequest($url);
		$access_token = json_decode($access_token_json, true);
		$code = $access_token['errcode'] ?: 0;
		if ($code == 0) {
			$data->expires_time = time() + 3000;
			$data->access_token = $access_token;
			set_php_file($token_file_name, json_encode($data));

			$access_token = $access_token['access_token'];
		} else {
			if ($count < 3) {
				++$count;
				get_access_token($token_file_name, $type, $count);
			} else {
				unlink(RUNTIME_PATH . '/' . $token_file_name);
				apiReturn(2, $access_token['errmsg']);
			}
		}
	} else {
		$access_token = $data->access_token->access_token;
	}

	return $access_token;
}

function get_php_file($filename)
{
	if (!is_file(RUNTIME_PATH . '/' . $filename)) {
		$data['expires_time'] = 0;
		$data['jsapi_ticket'] = '';
		set_php_file($filename, json_encode($data));
	}

	return file_get_contents(RUNTIME_PATH . '/' . $filename);
}

function set_php_file($filename, $content)
{
	file_put_contents(RUNTIME_PATH . '/' . $filename, $content);
}

/**
 * 注册用户 及 绑定用户
 * @param        array        $user_data        当前用户信息
 * @return array
 * */
function bindUser($user_data)
{
	$time = time();

	$user_info = Db::name('user')->where(['openid' => $user_data['openid']])->find();
	if ($user_info) {
		// 直接返回用户id和用户手机号
		$return_data = [
			'user_id' => $user_info['id'],
			'mobile' => $user_info['mobile'] ?: ''
		];

		return $return_data;
	} else {
		// 新用户

		//注册用户信息 及 绑定
		$user_data['create_time'] = $time;

		$return_user_id = Db::name('user')->insertGetId($user_data);

		$return_data = [
			'user_id' => $return_user_id,
			'mobile' => ''
		];

		return $return_data;
	}
}

/**
 * 生成用户分享码（公众号二维码[带用户id]）
 * @param        string        $user_id        用户id
 * @return string
 * */
function createUserQr($user_id)
{
	$qr = Db::name('user')->where(['id' => $user_id])->value('qr');
	if ($qr == 0) {
		$access_token = get_access_token();

		$data = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "' . $user_id . '"}}}';

		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $access_token;

		$res = httpsRequest($url, $data);
		echo "<pre>";
		print_r($res);
		exit;
		$result = json_decode($res, true);
		$ticket = $result['ticket'];
		$img = file_get_contents('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $ticket);

		$dir = './uploads/userQr/';
		if (!is_dir($dir)) mkdir($dir);

		$path = $dir . 'userQr_' . $user_id . '.jpg';

		$data = [
			'path' => substr($path, 1),
			'create_time' => time()
		];
		$id = Db::name('picture')->insertGetId($data);

		if ($id) {
			file_put_contents($path, $img);

			Db::name('user')->where(['id' => $user_id])->setField('qr', $id);

			return $id;
		}
	}
}

/**
 * 隐藏手机号
 * @param        string        $tel        手机号
 * @return string
 * */
function hideMobile($tel)
{
	return $tel ? substr_replace($tel, '****', 3, 4) : '';
}

/**
 * 过滤文本中的emoji表情包（输出到excel文件中会导致问题）
 * @param        string        $text        原文本
 * @return string 过滤emoji表情包后的文本
 */
function removeEmoji($text)
{
	$len = mb_strlen($text);
	$newText = '';
	for ($i = 0; $i < $len; $i++) {
		$str = mb_substr($text, $i, 1, 'utf-8');
		if (strlen($str) >= 4) continue;//emoji表情为4个字节
		$newText .= $str;
	}

	return $newText;
}